package com.itheima.boottlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.boottlias.domain.pojo.Clazz;
import com.itheima.boottlias.domain.query.QueryParam;
import com.itheima.boottlias.domain.vo.PageResult;
import com.itheima.boottlias.ex.CustomException;
import com.itheima.boottlias.mapper.ClazzMapper;
import com.itheima.boottlias.mapper.EmpMapper;
import com.itheima.boottlias.mapper.StudentMapper;
import com.itheima.boottlias.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ghy
 * @version 1.0
 * @since 2025-07-14 12:19
 */
@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private EmpMapper empMapper;

    @Override
    public PageResult<Clazz> pageQuery(QueryParam queryParam) {
        PageHelper.startPage(queryParam.getPage(), queryParam.getPageSize());
        Page<Clazz> page = clazzMapper.findByCondition(queryParam);
        List<Clazz> clazzList = page.getResult().stream()
                .peek(item -> {
                    LocalDate beginDate = item.getBeginDate();
                    LocalDate endDate = item.getEndDate();
                    LocalDate now = LocalDate.now();
                    if(now.isBefore(beginDate)) {
                        item.setStatus("未开班");
                    } else if(now.isAfter(endDate)) {
                        item.setStatus("已结课");
                    } else {
                        item.setStatus("在读");
                    }
                }).toList();
        return new PageResult<>(page.getTotal(), clazzList);
    }

    @Override
    public List<Clazz> list() {
        return clazzMapper.findAll();
    }

    @Override
    public void deleteById(Integer id) {
        Long count = studentMapper.countByClazzId(id);
        if(count > 0) {
            throw new CustomException("该班级中有若干学生，不能删除!!");
        }
        clazzMapper.deleteById(id);
    }

    @Override
    public void add(Clazz clazz) {
        LocalDateTime now = LocalDateTime.now();
        clazz.setCreateTime(now);
        clazz.setUpdateTime(now);
        clazzMapper.insert(clazz);
    }

    @Override
    public Clazz findById(Integer id) {
        return clazzMapper.findById(id);
    }

    @Override
    public void updateById(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateById(clazz);
    }
}
